const express = require('express');
const router = express.Router();
const { generateProof } = require('../services/zkService');
const { ethers } = require('ethers');
const { verifyProof } = require('../services/zkService');
const Transaction = require('../models/transaction');
const User = require('../models/user');
const Loan = require('../models/loan');
const { readJsonFile, writeJsonFile } = require('../utils/fileUtils');

// POST /zk/generate-proof
router.post('/generate-proof', async (req, res) => {
  const { creditScore, threshold } = req.body;
  if (typeof creditScore !== 'number' || typeof threshold !== 'number') {
    return res.status(400).json({ error: 'Invalid input' });
  }
  try {
    const proof = await generateProof(creditScore, threshold);
    res.json({ proof });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// System balance
let systemBalance = 10000; // Initial system balance: 10000 yuan

// Get system balance (admin only)
router.get('/system-balance', async (req, res) => {
  try {
    if (req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: 'Unauthorized' });
    }
    res.json({ success: true, balance: systemBalance });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// Get all transactions (admin only)
router.get('/transactions', async (req, res) => {
  try {
    if (req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: 'Unauthorized' });
    }
    const transactions = await Transaction.find().sort({ timestamp: -1 });
    res.json({ success: true, transactions });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// Verify credit proof
router.post('/verify-proof', async (req, res) => {
  try {
    const { userId, verificationCode } = req.body;

    // Verify the proof using zero-knowledge proof verification
    const isValid = await verifyProof(verificationCode);

    if (!isValid) {
      return res.json({ success: false, message: 'Invalid proof' });
    }

    // Record the proof fee transaction
    systemBalance += 10; // 10 yuan proof fee

    await Transaction.create({
      user: userId,
      amount: 10,
      transactionType: 'PROOF_FEE',
      timestamp: new Date()
    });

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// Create loan
router.post('/lend', async (req, res) => {
  try {
    const { userId, amount, duration, interestRate } = req.body;

    // Read users data
    const users = await readJsonFile('users.json');
    const user = users.find(u => u.id === parseInt(userId));

    if (!user) {
      return res.json({ success: false, message: '用户不存在' });
    }

    // Check if user has valid proof
    const proofs = await readJsonFile('credit_proofs.json');
    const hasValidProof = proofs.some(p =>
      p.userId === parseInt(userId) &&
      p.expiresAt > Date.now()
    );

    if (!hasValidProof) {
      return res.json({ success: false, message: '没有有效的信用证明' });
    }

    // Read transactions data
    const transactions = await readJsonFile('transactions.json');

    // Create new transaction
    const newTransaction = {
      id: transactions.length + 1,
      fromUserId: parseInt(userId), // 放贷人ID
      toUserId: 2, // 系统账户
      amount: parseInt(amount),
      interestRate: interestRate,
      totalAmount: parseInt(amount) + (parseInt(amount) * interestRate * duration / 36500), // 本金 + 利息
      timestamp: new Date().toISOString(),
      type: 'lend', // 改为lend类型
      status: 'pending',
      dueDate: new Date(Date.now() + duration * 24 * 60 * 60 * 1000).toISOString(),
      duration: duration
    };

    // Update user balance
    user.balance -= parseInt(amount); // 放贷时减少余额
    user.loanHistory.push(newTransaction.id);

    // Save updates
    await writeJsonFile('users.json', users);
    await writeJsonFile('transactions.json', [...transactions, newTransaction]);

    res.json({
      success: true,
      message: '放贷成功',
      transaction: newTransaction
    });
  } catch (error) {
    console.error('放贷失败:', error);
    res.status(500).json({ success: false, message: '放贷失败' });
  }
});

// Repay loan
router.post('/repay', async (req, res) => {
  try {
    const { userId, loanId } = req.body;

    // Read users data
    const users = await readJsonFile('users.json');
    const user = users.find(u => u.id === parseInt(userId));

    if (!user) {
      return res.json({ success: false, message: '用户不存在' });
    }

    // Read transactions data
    const transactions = await readJsonFile('transactions.json');
    const transaction = transactions.find(t => t.id === parseInt(loanId));

    if (!transaction) {
      return res.json({ success: false, message: '交易不存在' });
    }

    if (transaction.type !== 'loan' || transaction.status !== 'pending') {
      return res.json({ success: false, message: '无效的还款请求' });
    }

    // Check if user has enough balance
    if (user.balance < transaction.amount) {
      return res.json({ success: false, message: '余额不足' });
    }

    // Update transaction status
    transaction.status = 'completed';
    transaction.repaidAt = new Date().toISOString();

    // Update user balance
    user.balance -= transaction.amount;

    // Calculate credit score change based on repayment timing
    const dueDate = new Date(transaction.dueDate);
    const repaidAt = new Date(transaction.repaidAt);
    const daysLate = Math.floor((repaidAt - dueDate) / (24 * 60 * 60 * 1000));

    let scoreChange = 10; // Default for on-time repayment
    let reason = '按时还款';

    if (daysLate > 0) {
      if (daysLate <= 7) {
        scoreChange = -20;
        reason = '逾期1-7天';
      } else if (daysLate <= 30) {
        scoreChange = -50;
        reason = '逾期8-30天';
      } else {
        scoreChange = -100;
        reason = '逾期30天以上';
      }
    }

    // Update credit score
    const newScore = Math.max(600, Math.min(850, user.creditScore + scoreChange));
    user.creditScore = newScore;

    // Record credit history
    user.creditHistory.push({
      timestamp: new Date().toISOString(),
      type: 'change',
      score: newScore,
      change: scoreChange,
      description: reason
    });

    // Save updates
    await writeJsonFile('users.json', users);
    await writeJsonFile('transactions.json', transactions);

    res.json({
      success: true,
      message: '还款成功',
      repaidAmount: transaction.amount,
      newBalance: user.balance,
      creditScore: user.creditScore,
      scoreChange
    });
  } catch (error) {
    console.error('还款失败:', error);
    res.status(500).json({ success: false, message: '还款失败' });
  }
});

// Collect loan repayment
router.post('/collect-loan', async (req, res) => {
  try {
    const { userId, transactionId } = req.body;

    // Read users data
    const users = await readJsonFile('users.json');
    const user = users.find(u => u.id === parseInt(userId));

    if (!user) {
      return res.json({ success: false, message: '用户不存在' });
    }

    // Read transactions data
    const transactions = await readJsonFile('transactions.json');
    const transaction = transactions.find(t => t.id === parseInt(transactionId));

    if (!transaction) {
      return res.json({ success: false, message: '交易不存在' });
    }

    if (transaction.type !== 'lend' || transaction.status !== 'pending') {
      return res.json({ success: false, message: '无效的收回请求' });
    }

    // Check if the loan is due
    const now = new Date();
    const dueDate = new Date(transaction.dueDate);

    if (now < dueDate) {
      return res.json({
        success: false,
        message: '贷款未到期，不能收回',
        dueDate: transaction.dueDate,
        remainingDays: Math.ceil((dueDate - now) / (24 * 60 * 60 * 1000))
      });
    }

    // Update transaction status
    transaction.status = 'completed';
    transaction.collectedAt = new Date().toISOString();

    // Update user balance with total amount (principal + interest)
    user.balance += transaction.totalAmount;

    // Save updates
    await writeJsonFile('users.json', users);
    await writeJsonFile('transactions.json', transactions);

    res.json({
      success: true,
      message: '收回贷款成功',
      collectedAmount: transaction.totalAmount,
      newBalance: user.balance
    });
  } catch (error) {
    console.error('收回贷款失败:', error);
    res.status(500).json({ success: false, message: '收回贷款失败' });
  }
});

// Get all loans
router.get('/all-loans', async (req, res) => {
  try {
    const transactions = await readJsonFile('transactions.json');
    const users = await readJsonFile('users.json');

    const loans = transactions
      .filter(t => t.type === 'loan')
      .map(loan => {
        const user = users.find(u => u.id === loan.toUserId);
        return {
          ...loan,
          username: user ? user.username : 'Unknown'
        };
      });

    res.json({
      success: true,
      loans: loans
    });
  } catch (error) {
    console.error('获取借款记录失败:', error);
    res.status(500).json({ success: false, message: '获取借款记录失败' });
  }
});

// Get all lending records
router.get('/all-lends', async (req, res) => {
  try {
    const transactions = await readJsonFile('transactions.json');
    const users = await readJsonFile('users.json');

    const lends = transactions
      .filter(t => t.type === 'lend')
      .map(lend => {
        const user = users.find(u => u.id === lend.fromUserId);
        return {
          ...lend,
          username: user ? user.username : 'Unknown'
        };
      });

    res.json({
      success: true,
      lends: lends
    });
  } catch (error) {
    console.error('获取放贷记录失败:', error);
    res.status(500).json({ success: false, message: '获取放贷记录失败' });
  }
});

module.exports = router; 